﻿using System;
using System.Collections.Generic;
using System.Linq;
using Altairis.FluffyCloud.Data;
using Altairis.FluffyCloud.Storage;

namespace Altairis.FluffyCloud.WebCore.Pages.My {

    public partial class Settings : DbPage {
        private User currentUser;

        public IEnumerable<Role> RoleList_GetData() {
            var u = this.DbContext.Users.Single(x => x.UserName.Equals(this.User.Identity.Name));
            return u.Roles.OrderBy(x => x.RoleName).ToArray();
        }

        public IEnumerable<object> ThemeList_GetData() {
            // Get JSON serialized list of themes
            var themesJson = System.IO.File.ReadAllText(this.Server.MapPath("~/Content/Themes/list.json"));

            // Load it into structure
            var themes = new[] {new {
                Name = string.Empty,
                BundleUrl = string.Empty,
                Files = new string[] { string.Empty }
            }};
            themes = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(themesJson, themes);

            // Populate radiobutton
            foreach (var theme in themes) {
                yield return new {
                    Text = theme.Name,
                    Value = theme.BundleUrl
                };
            }
            yield return new {
                Text = "Jiné - zadejte URL:",
                Value = string.Empty
            };
        }

        protected void ChangeSecurityCodeButton_Click(object sender, EventArgs e) {
            // Get user
            var u = this.DbContext.Users.Single(x => x.UserName.Equals(this.User.Identity.Name));

            // Get random code
            var code = new byte[32];
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) {
                rng.GetBytes(code);
            }

            // Change security code
            u.SecurityCode = Altairis.Web.Convert.ToUrlSafeBase64String(code, true);

            // Save changes
            this.DbContext.SaveChanges();
            this.SecurityCodeChangedLiteral.Visible = true;
        }

        protected void ChangeToGravatarButton_Click(object sender, EventArgs e) {
            var result = UserIcon.Delete(this.currentUser.UserName);
            if (result) {
                this.IconChangeSuccessLiteral.Visible = true;
                this.IconMultiView.SetActiveView(this.ViewGravatar);
            }
            else {
                this.IconChangeFailureLiteral.Visible = true;
            }
        }

        protected void IconUploadButton_Click(object sender, EventArgs e) {
            if (this.IconFileUpload.PostedFile == null || this.IconFileUpload.PostedFile.ContentLength == 0) {
                // No file was posted
                this.IconChangeFailureLiteral.Visible = true;
                return;
            }

            // Try to process posted file
            var result = UserIcon.Upload(this.currentUser.UserName, this.IconFileUpload.PostedFile.InputStream);
            if (result) {
                this.IconChangeSuccessLiteral.Visible = true;
                this.IconMultiView.SetActiveView(this.ViewLocal);
            }
            else {
                this.IconChangeFailureLiteral.Visible = true;
            }
        }

        protected void Page_Load(object sender, EventArgs e) {
            this.currentUser = this.DbContext.Users.Single(x => x.UserName.Equals(this.User.Identity.Name));

            if (!this.IsPostBack) {
                // Process themes
                this.ThemeList.DataBind();
                if (string.IsNullOrWhiteSpace(this.currentUser.ThemeCssUrl)) {
                    // No theme chosen - use first (default)
                    this.ThemeList.SelectedIndex = 0;
                }
                else {
                    var item = this.ThemeList.Items.FindByValue(this.currentUser.ThemeCssUrl);
                    if (item == null) {
                        // Custom theme - use last (custom)
                        this.ThemeList.SelectedIndex = this.ThemeList.Items.Count - 1;
                        this.CustomUrlTextBox.Text = this.currentUser.ThemeCssUrl;
                    }
                    else {
                        // Embedded theme - select it
                        item.Selected = true;
                    }
                }

                // Process user icon
                if (UserIcon.Verify(this.currentUser.UserName)) {
                    // User has local icon
                    this.IconMultiView.SetActiveView(this.ViewLocal);
                }
                else {
                    // User has Gravatar
                    this.IconMultiView.SetActiveView(this.ViewGravatar);
                }

                // Process other things
                this.SendNewMessagesToEmailCheckBox.Checked = this.currentUser.SendNewMessagesToEmail;
            }
        }

        protected void SubmitChangesButton_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            // Read changes from UI
            this.currentUser.SendNewMessagesToEmail = this.SendNewMessagesToEmailCheckBox.Checked;
            this.currentUser.ThemeCssUrl = this.ThemeList.SelectedValue;
            if (string.IsNullOrWhiteSpace(this.currentUser.ThemeCssUrl)) this.currentUser.ThemeCssUrl = this.CustomUrlTextBox.Text;
            if (string.IsNullOrWhiteSpace(this.currentUser.ThemeCssUrl)) this.currentUser.ThemeCssUrl = null;

            // Save changes
            this.DbContext.SaveChanges();
            this.Response.RedirectToRoute("MyHome");
        }
    }
}